// 一旦点击到外面，就消失！
// 只有一层，暂时没有考虑一个界面再加一个combox的情况！

class MainContexMenu extends eui.UILayer {
	Main: egret.DisplayObject;

	constructor(Main: egret.DisplayObject) {
		super();
		this.Main = Main;
		Main.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTouchBeginMain, this);
	}

	contexMenu: egret.DisplayObject;

	funnClose: ()=>void;

	self: any;

	private onTouchBeginMain(e: egret.TouchEvent): void {
		if (this.contexMenu == null) return;
		const { target } = e;
		if (isSelfOrParent(target, this.contexMenu)) {
			return;
		}
		this.clearCurrentContex();
	}

	clearContexMenu(menu: egret.DisplayObject): boolean {
		if (this.contexMenu === menu) {
			this.clearCurrentContex();
			return true;
		}
		return false;
	}

	clearCurrentContex(): boolean {
		if (this.contexMenu) {
			const menu = this.contexMenu;
			const func = this.funnClose;
			const { self } = this;
			this.contexMenu = null;
			this.funnClose = null;
			this.self = null;
			this.removeChild(menu);
			if (func) {
				func.apply(self);
			}
			return true;
		}
		return false;
	}

	showContexMenu(
		menus: string[],
		callback: (event:string)=>void,
		self: egret.DisplayObject,
		width: number,
	): ContexMenu {
		const menu = new ContexMenu();
		menu.showContexMenu(menus, callback, self, width);

		const pt = self.localToGlobal(0, 0);
		const pt2 = this.globalToLocal(pt.x, pt.y);
		menu.x = pt2.x;
		menu.y = pt2.y;
		this.addContex(menu, null, null);
		return menu;
	}

	addContex(menu: egret.DisplayObject, funcClose: ()=>void, self: any): void {
		this.clearCurrentContex();
		this.contexMenu = menu;
		this.funnClose = funcClose;
		this.self = self;
		this.addChild(menu);
	}

	closeChild(win: ModalWin): void {
		this.clearContexMenu(win);
	}
}
